<template>
	<div class="app-container">
    <!-- 搜索 -->
    <div class="filter-container tw-filter">
      <el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-edit" v-has="$store.state.user.btn_common+'add'" @click="handleAdd()">添加</el-button>
      <el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-delete" v-has="$store.state.user.btn_common+'del'" @click="handleDelete()">批量删除</el-button>

      <el-input v-model="queryList.name" placeholder="请输入地区名称" class="filter-item tw-filter-input" clearable/>

      <el-button v-waves class="filter-item tw-filter-button" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

    <!-- 表格内容 -->
    <el-table
      v-loading="listLoading"
      :data="tableList"
      @selection-change="handleSelectionChange"
      border fit highlight-current-row style="width: 100%;"
    >
    	<el-table-column type="selection" width="50" />
    	<el-table-column label="排序" prop="sort_id" align="center" width="80" v-has="$store.state.user.btn_common+'edit'">
    		<template slot-scope="{row}">
    			<el-input v-model="row.sort_id" class="edit-input" size="small" @change="updateSort(row.id,row.sort_id)" />
    		</template>
    	</el-table-column>
    	<el-table-column label="ID" prop="id" align="center" width="80" />
    	<el-table-column label="城市行政代码" prop="adcode" align="center" />
      <el-table-column label="地区名称" prop="name" align="center" />
      <el-table-column label="所属大区" prop="region" align="center" />
      <el-table-column label="所在层级" prop="deep" align="center" />
      <!-- <el-table-column label="上级地区id" prop="parent_id" align="center" /> -->
    	<el-table-column label="操作" align="center" width="300px" class-name="small-padding fixed-width">
    		<template slot-scope="{row}">
						<el-button size="mini" v-if="row.deep < 4" @click="getList(row.id)">查看下级</el-button>
						<el-button size="mini" v-if="row.parent_id > 0" @click="handleReturn(row.parent_id)">返回上级</el-button>
    			<el-button size="mini" v-has="$store.state.user.btn_common+'edit'" @click="handleEdit(row.id)">编辑</el-button>
    			<el-button size="mini" v-has="$store.state.user.btn_common+'del'" @click="handleDelete(row.id)">删除</el-button>
    		</template>
    	</el-table-column>
    </el-table>
    <pagination v-show="isPage && listTotal > 0" :total="listTotal" :page.sync="queryList.curpage" :limit.sync="queryList.page" @pagination="getList(queryList.parent_id)" />

    <!-- 添加/编辑 -->
    <el-dialog width="45%" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form label-position="right" label-width="180px" ref="dataForm" :rules="rules" :model="form">

        <el-form-item label="地区名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="上级地区" prop="parent_id">
          <el-select v-model="form.area1" @change="getCityList(form.area1)" style="width: 25%;" class="filter-item" placeholder="请选择省">
            <el-option v-for="item in provinceList" :key="item.id" filter="false" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-model="form.area2" @change="getAreaList(form.area2)" style="width: 25%;" class="filter-item" placeholder="请选择市">
            <el-option v-for="item in cityList" :key="item.id" filter="false" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-model="form.area3" @change="getTownList(form.area3)" style="width: 25%;" class="filter-item" placeholder="请选择县/区">
            <el-option v-for="item in areaList" :key="item.id" filter="false"
              :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-model="form.area4" style="width: 25%;" class="filter-item" placeholder="请选择乡/镇">
            <el-option v-for="item in townList" :key="item.id" filter="false"
              :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市行政代码" prop="adcode">
          <el-input v-model="form.adcode" />
        </el-form-item>
        <el-form-item label="所属大区" prop="region">
          <el-input v-model="form.region" />
        </el-form-item>
        <el-form-item label="排序" prop="sort_id">
          <el-input v-model="form.sort_id" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">提交</el-button>
      </div>
    </el-dialog>
	</div>
</template>

<script>
  import Pagination from '@/components/Pagination' // 基于el分页的二次封装
  import waves from '@/directive/waves' // waves directive
  import UploadOne from '@/components/Upload/UploadOne'

	export default {
		components: { Pagination, UploadOne },
		directives: { waves },
		data() {
			return {
				// 数据列表
				listLoading: true,
				listTotal: 0,
				isPage: false,
				tableList: [],
				multipleSelection: [],//多选数据
				// 添加/编辑弹窗
				dialogFormVisible: false,
				dialogStatus: '',
				textMap: {
					update: '编辑',
					create: '添加'
				},
        //键字段
        keyName: 'id',
        apiPath: 'project.area',

        // 搜索数据
        queryList: {
        	page: this.$store.state.settings.page, // 每页显示数量
        	curpage: 1, // 当前页码
          parent_id: 0,
        	name: '',
        },

        // 表单数据
        form: {
          id: '',
          name: '', //地区名称
          area1: '',
          area2: '',
          area3: '',
          area4: '',
          parent_id: 0,
          adcode: '', //城市行政代码
          region: '', //所属大区
          sort_id: 255 , //排序
        },
        // 重置数据
        formReset: {
          id: '',
          name: '', //地区名称
          area1: '',
          area2: '',
          area3: '',
          area4: '',
          parent_id: 0,
          adcode: '', //城市行政代码
          region: '', //所属大区
          sort_id: 255 , //排序
        },

        // 验证
        rules: {
        	name: [{ required: true, message: '请输入地区名称！', trigger: 'change' }]
        },

				// 上级地区列表
				provinceList: [],//省列表
				cityList: [], //市列表
				areaList: [], //县/区列表
				townList: [], //乡/镇列表
			}
		},
		created() {
			//获取数据列表
			this.getList()
		},
		methods: {
      // 获取省列表
      getProvinceList() {
        this.provinceList = [];
        this.cityList = [];
        this.areaList = [];
        this.townList = [];
        this.form.area1 = ''
        this.form.area2 = ''
        this.form.area3 = ''
        this.form.area4 = ''

      	this.$api.fetchList({parent_id: 0}, this.apiPath).then(response => {
      		//this.provinceList = JSON.parse(JSON.stringify(response.list));
      		// 数据处理
      		response.list.unshift({
      			id: '',
      			name: '请选择省'
      		})
      		this.provinceList = response.list
      	})
      },
      // 获取市
      getCityList(id = 0) {
        this.cityList = [];
        this.areaList = [];
        this.townList = [];
        this.form.area2 = ''
        this.form.area3 = ''
        this.form.area4 = ''

      	this.$api.fetchList({parent_id: id}, this.apiPath).then(response => {
      		// 数据处理
      		response.list.unshift({
      			id: '',
      			name: '请选择市'
      		})
      		this.cityList = response.list
      	})
      },
      // 获取县/区
      getAreaList(id = 0) {
        this.areaList = [];
        this.townList = [];
        this.form.area3 = ''
        this.form.area4 = ''

      	this.$api.fetchList({parent_id: id}, this.apiPath).then(response => {
      		// 数据处理
      		response.list.unshift({
      			id: '',
      			name: '请选择县/区'
      		})
      		this.areaList = response.list
      	})
      },
      // 获取乡/镇
      getTownList(id = 0) {
        this.townList = [];
        this.form.area4 = ''

      	this.$api.fetchList({parent_id: id}, this.apiPath).then(response => {
      		// 数据处理
      		response.list.unshift({
      			id: '',
      			name: '请选择乡/镇'
      		})
      		this.townList = response.list
      	})
      },

      //点击返回
      handleReturn(parent_id=0) {
        // 获取详情
        this.$api.getDetail({ id: parent_id}, this.apiPath).then(response => {
          // 重新获取列表
          this.queryList.curpage = 1
          this.tableList = []
          this.getList(response.detail.parent_id)
        })
      },

      // 搜索
      handleFilter() {
      	this.queryList.curpage = 1
      	this.tableList = []
        this.listTotal = 0
      	this.getList()
      },
      // 列表选择
      handleSelectionChange(val) {
      	this.multipleSelection = val
      },
      // 重置form
      resetForm() {
      	this.form = JSON.parse(JSON.stringify(this.formReset))
      },
			// 获取数据列表
			getList(id = 0) {
				this.listLoading = true

        this.queryList.parent_id = id;
				this.$api.fetchList(this.queryList, this.apiPath).then(response => {
					this.tableList = response.list
					this.listTotal = response.list_count
					this.isPage = response.is_page
          this.listLoading = false
				})
			},
			// 添加
			handleAdd() {
			  this.resetForm()
        // 获取省列表
        this.getProvinceList()

			  this.dialogStatus = 'create'
			  this.dialogFormVisible = true
			  this.$nextTick(() => {
			    this.$refs['dataForm'].clearValidate()
			  })
			},
      // 编辑
      handleEdit(id = 0) {
        this.resetForm()

        // 获取省列表
        this.getProvinceList()

        // 获取详情
        this.$api.getDetail({ id: id}, this.apiPath).then(response => {
          //数据处理
          for(let key in this.form){
            if(response.detail.hasOwnProperty(key)){
              this.form[key] = response.detail[key]
            }
          }

          // 数据处理
          response.detail.cityList.unshift({
          	id: '',
          	name: '请选择市'
          })
          this.cityList = response.detail.cityList
          response.detail.areaList.unshift({
          	id: '',
          	name: '请选择县/区'
          })
          this.areaList = response.detail.areaList
          response.detail.townList.unshift({
          	id: '',
          	name: '请选择乡/镇'
          })
          this.townList = response.detail.townList
        })

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        })
      },
      // 添加-数据提交
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$api.add(this.form, this.apiPath).then(() => {
              // 重新获取列表
              this.queryList.curpage = 1
              this.tableList = []
              this.getList(this.queryList.parent_id)

              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 编辑-数据提交
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$api.edit(this.form, this.apiPath).then(response => {
              // 重新获取列表
              this.getList(this.queryList.parent_id)

              this.dialogFormVisible = false
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 删除
      handleDelete(id = 0) {
        let current = this
        let id_str = ''
        if (!id) {
          // 多选
          if (!this.multipleSelection.length) {
            this.$message({
              message: '请选择删除的条目！',
              type: 'warning'
            })
            return false
          }
          // 数据处理
          this.multipleSelection.forEach(item => {
            id_str += item[current.keyName] + ','
          })
        } else {
          id_str = id
        }

        // 提交数据
        this.$confirm('确认删除数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.del({ id_str: id_str }, this.apiPath).then(response => {
            // 重新获取列表
            this.getList(this.queryList.parent_id)
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          })
        })
      },
			// 排序
			updateSort(id = 0, sort = '') {
				this.$api.editSort({
					id: id,
					sort: sort
				}, this.apiPath).then(response => {
					this.$message({
						message: '排序成功',
						type: 'success'
					})
				})
			}

		}
	}
</script>
